package com.github.tetrisgame.ui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.github.tetrisgame.model.Block;
import com.github.tetrisgame.utils.Constants;

public class PreviewView extends View {
    private int[][] boards;
    private Bitmap mBitmap;
    private Rect mRect = new Rect();
    private int mSize = Constants.SIZE/2;

    public PreviewView(Context context) {
        this(context,null);
    }

    public PreviewView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int mWidth = 3 * mSize;
        int mHeight = 3 * mSize;

        setMeasuredDimension(mWidth,mHeight);
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        if (boards == null) return;

        for (int i = 0; i < boards.length; i++) {
            for (int j = 0; j < boards[0].length; j++) {
                if (boards[i][j] == 1){
                    //绘制方格
                    mRect.left = j * mSize;
                    mRect.top = i * mSize;
                    mRect.right = mRect.left + mSize;
                    mRect.bottom = mRect.top + mSize;
                    canvas.drawBitmap(mBitmap,null,mRect,null);
                }
            }
        }
    }

    //显示预览视图
    public void showBlock(Block previewBlock) {
        //获取当前这个block对应的二维数组
        boards = previewBlock.getShape();

        //将方块对应的图片资源抓华为Bitmap
        mBitmap = BitmapFactory.decodeResource(getResources(),previewBlock.imageResource);

        //刷新界面 onDraw()方法会重新调用
        invalidate();
    }
}
